<?php

/**
 * Name: 头像服务
 * User: Silent
 * Date: 2025-11-17
 * Time: 17:40:00
 */

namespace App\Services\Avatar;

use App\Services\Avatar\AvatarGeneratorService;
use App\Services\Upload\OssUploadService;
use Exception;

class AvatarService
{
    protected $avatarGenerator;
    protected $ossUpload;
    
    public function __construct(
        AvatarGeneratorService $avatarGenerator,
        OssUploadService $ossUpload
    ) {
        $this->avatarGenerator = $avatarGenerator;
        $this->ossUpload = $ossUpload;
    }

    /**
     * 根据昵称生成头像并上传到OSS
     *
     * @param string $nickname 昵称
     * @param string $userId 用户ID（可选）
     * @param int $size 头像尺寸，默认200
     * @return array ['success' => bool, 'url' => string, 'message' => string]
     */
    public function generateAndUploadAvatar($nickname, $userId = null, $size = 200)
    {
        try {
            // 检查OSS配置
            if (!$this->ossUpload->isConfigured()) {
                return [
                    'success' => false,
                    'url' => '',
                    'message' => 'OSS配置未完成，无法上传头像'
                ];
            }

            // 生成头像图像数据
            $imageData = $this->avatarGenerator->generateAvatar($nickname, $size);
            
            if (!$imageData) {
                return [
                    'success' => false,
                    'url' => '',
                    'message' => '头像生成失败'
                ];
            }

            // 生成文件名
            $filename = $this->ossUpload->generateAvatarFilename($nickname, $userId);
            
            // 上传到OSS
            $uploadResult = $this->ossUpload->uploadContent($imageData, $filename);
            
            if (!$uploadResult['success']) {
                return $uploadResult;
            }

            \Log::info('头像生成并上传成功', [
                'nickname' => $nickname,
                'user_id' => $userId,
                'filename' => $filename,
                'url' => $uploadResult['url']
            ]);

            return [
                'success' => true,
                'url' => $uploadResult['url'],
                'message' => '头像生成并上传成功',
                'filename' => $filename,
                'oss_path' => $uploadResult['oss_path']
            ];

        } catch (Exception $e) {
            \Log::error('头像生成上传失败', [
                'nickname' => $nickname,
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'url' => '',
                'message' => '头像处理异常：' . $e->getMessage()
            ];
        }
    }

    /**
     * 批量为多个用户生成头像
     *
     * @param array $users 用户数组，每个元素包含nickname和id
     * @return array
     */
    public function batchGenerateAvatars($users)
    {
        $results = [];
        $successCount = 0;
        $failCount = 0;

        foreach ($users as $user) {
            $nickname = $user['nickname'] ?? '';
            $userId = $user['id'] ?? null;

            if (empty($nickname)) {
                $results[] = [
                    'user_id' => $userId,
                    'success' => false,
                    'message' => '昵称为空'
                ];
                $failCount++;
                continue;
            }

            $result = $this->generateAndUploadAvatar($nickname, $userId);
            $results[] = array_merge($result, ['user_id' => $userId]);

            if ($result['success']) {
                $successCount++;
            } else {
                $failCount++;
            }
        }

        return [
            'total' => count($users),
            'success_count' => $successCount,
            'fail_count' => $failCount,
            'results' => $results
        ];
    }

    /**
     * 预览头像（返回base64编码的图像数据）
     *
     * @param string $nickname
     * @param int $size
     * @return array
     */
    public function previewAvatar($nickname, $size = 200)
    {
        try {
            $imageData = $this->avatarGenerator->generateAvatar($nickname, $size);
            
            if (!$imageData) {
                return [
                    'success' => false,
                    'data' => '',
                    'message' => '头像生成失败'
                ];
            }

            $base64Data = base64_encode($imageData);
            $dataUrl = 'data:image/png;base64,' . $base64Data;

            return [
                'success' => true,
                'data' => $dataUrl,
                'message' => '头像预览生成成功'
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'data' => '',
                'message' => '头像预览生成失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 获取头像服务状态
     *
     * @return array
     */
    public function getServiceStatus()
    {
        $ossConfig = $this->ossUpload->getConfigInfo();
        
        // 测试头像生成
        $testGeneration = $this->avatarGenerator->generateAvatar('测试', 100) !== false;
        
        return [
            'avatar_generation' => [
                'available' => $testGeneration,
                'message' => $testGeneration ? '头像生成功能正常' : '头像生成功能异常'
            ],
            'oss_upload' => [
                'configured' => $ossConfig['configured'],
                'config' => $ossConfig,
                'message' => $ossConfig['configured'] ? 'OSS配置正常' : 'OSS配置缺失'
            ],
            'overall_status' => $testGeneration && $ossConfig['configured'] ? 'ready' : 'error'
        ];
    }

    /**
     * 删除用户头像
     *
     * @param string $ossPath OSS路径
     * @return bool
     */
    public function deleteAvatar($ossPath)
    {
        return $this->ossUpload->deleteFile($ossPath);
    }
}
